package com.gitee.srurl.system.exception.handle;

import com.gitee.srurl.core.exception.ServiceException;
import com.gitee.srurl.system.util.response.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author zxw
 * @date 2022/12/4
 */
@Slf4j
@RestControllerAdvice
public class ExceptionHandle {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                       HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址:'{}',不支持'{}'请求", requestURI, e.getMethod());
        return R.error("不支持的请求方式！");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public R<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {

        String requestURI = request.getRequestURI();
        log.error("请求地址:'{}',发生未知异常.", requestURI, e);
        return R.error("系统处理异常！");
    }

    /**
     * 拦截自定义服务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public R<Void> handleServiceException(ServiceException e) {

        return R.error(e.getCode(), e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public R<Void> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址:'{}',发生系统异常.", requestURI, e);
        return R.error("系统处理异常！");
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public R<Void> handleBindException(BindException e) {

        log.warn("校验异常:{}", e.getMessage());
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return R.error(message);
    }

    /**
     * 自定义验证异常
     */
    @SuppressWarnings("all")
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {

        log.warn("校验异常:{}", e.getMessage());
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return R.error(message);
    }
}
